import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Checkbox, message } from 'antd';
import { WeaTableNew } from 'comsMobx';
import { WeaTab, WeaLocaleProvider, WeaButtonIcon } from 'ecCom';
import { AntdConfirm } from '../util';
import Edit from './Edit';

const { WeaTable } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const showName = 'rule';

@inject('settingStore')
@observer
class Rule extends Component {
  static defaultProps = {
    prefixCls: 'email-setting-rule',
  };

  componentWillMount() {
    const {
      settingStore: { ruleStore, setStoreState },
    } = this.props;
    let rightMenuDatas = [
      {
        key: 'refresh',
        icon: <i className="icon-coms-Update-synchronization" />,
        content: getLabel(197, '搜索'),
        onClick: () => ruleStore.getEmailRuleList(),
      },
    ];
    setStoreState({ rightMenuDatas });
    ruleStore.getEmailRuleList();
  }

  componentWillUnmount() {
    const {
      settingStore: { ruleStore },
    } = this.props;
    ruleStore.clear();
  }

  checkChange = (e, record) => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    const { operateUserEmailRule, getEmailRuleList } = ruleStore;
    const isActive = e.target.checked ? '1' : '';
    let params = { operation: 'active', ruleId: record.id, isActive };
    operateUserEmailRule(params).then((res) => {
      if (res.flag) {
        getEmailRuleList('', true);
      }
    });
  };

  onOperatesClick = (record, index, operate) => {
    if (operate.index === '0') {
      // edit
      this.editRule(record);
    } else if (operate.index === '1') {
      // delete
      this.batchDel(record.randomFieldId);
    }
  };

  batchDel = (id) => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    const { operateUserEmailRule, getEmailRuleList, ruleTable } = ruleStore;
    const ruleId = id || toJS(ruleTable.selectedRowKeysAllPages).join();
    const params = { ruleId, operation: 'delete' };
    AntdConfirm('', () => {
      operateUserEmailRule(params).then((res) => {
        if (res.flag) {
          message.success(getLabel(83472, '删除成功！'));
          getEmailRuleList();
        } else {
          message.error(getLabel(384401, '删除失败，请重试！'));
        }
      });
    });
  };

  getColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        if (newColumn.dataIndex === 'ruleName') {
          return (
            <div
              onClick={() => this.editRule(record)}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
            />
          );
        } else if (newColumn.dataIndex == 'isActive') {
          return (
            <Checkbox
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Checkbox@oauagx@${showName}${record.id}`}
              checked={record.isActive * 1}
              onChange={e => this.checkChange(e, record)}
            />
          );
        }
        return <div dangerouslySetInnerHTML={{ __html: valueSpan }} />;
      };
      return newColumn;
    });
    return newColumns;
  };

  addRule = () => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    const { setStoreState, getEmailRuleCondition } = ruleStore;
    getEmailRuleCondition({ type: 'add' }, () => {
      setStoreState({
        editVisible: true,
        editTitle: getLabel(388533, '新建规则'),
        editType: 'new',
        isEdit: false,
      });
    });
  };

  editRule = (record) => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    const { setStoreState, getEditCondition } = ruleStore;
    const id = record.id;
    getEditCondition({ id, type: 'update' }, () => {
      setStoreState({
        ruleId: record.id,
        editVisible: true,
        editType: 'edit',
        editTitle: getLabel(84552, '编辑规则'),
        isEdit: true,
      });
    });
  };

  render() {
    const {
      prefixCls,
      settingStore: { ruleStore },
    } = this.props;
    const { ruleTable } = ruleStore;
    const tabButtons = [
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@s7uxlp@${showName}addRule`}
        buttonType="add"
        type="primary"
        onClick={this.addRule}
      />,
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@97fnq6@${showName}batchDel`}
        buttonType="del"
        type="primary"
        disabled={toJS(ruleTable.selectedRowKeysAllPages).length === 0}
        onClick={() => this.batchDel()}
      />,
    ];
    return (
      <div className={prefixCls}>
        <WeaTab
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTab@149kjq`}
          datas={[{ title: getLabel(19828, '邮件规则'), viewcondition: '0' }]}
          keyParam="viewcondition"
          buttons={tabButtons}
        />
        <WeaTable
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTable@ub26ul`}
          comsWeaTableStore={ruleTable}
          getColumns={this.getColumns}
          onOperatesClick={this.onOperatesClick}
          hasOrder
          needScroll
        />
        <Edit
          ecId={`${(this && this.props && this.props.ecId) || ''}_Edit@4w0usg`}
          class={prefixCls}
        />
      </div>
    );
  }
}

export default Rule;
